package top.codedance.iotp.tools.clientStatusMonitor;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import top.codedance.iotp.iot.sdk.*;
import top.codedance.iotp.iot.sdk.po.async.WsPushSubscriptionParam;
import top.codedance.iotp.tools.clientStatusMonitor.plugin.MyPlayer;
import top.codedance.iotp.tools.clientStatusMonitor.ui.AlertFrame;
import top.codedance.iotp.tools.clientStatusMonitor.ui.SettingsFrame;
import top.codedance.iotp.tools.clientStatusMonitor.util.FileTool;
import org.ini4j.Ini;
import org.ini4j.Wini;

import javax.swing.*;
import java.io.File;
import java.io.IOException;
import java.util.Random;

public class ClientStatusMonitorApplication {
    public static Wini ini = null;
    public static SettingsFrame sf;
    public static String websocketUrl = "ws://127.0.0.1:10013";
    public static String username = "";
    public static String password = "";
    public static AlertFrame alertFrame;
    public static MyPlayer offLinePlayer;
    public static MyPlayer onLinePlayer;
    private static String id = String.valueOf(new Random().nextLong());
    private static final String NAME = "clientStatusMonitor";
    public static String offlineWavPath;
    public static String onlineWavPath;
    public static String logoPath;
    public static String offlinePath;
    public static String onlinePath;
    public static String iniPath;
    public static boolean isStopWarning = false;

    public static void main(String[] args) {
        try {
            UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel()");
        } catch (Exception e) {
        }
        tmpInit();
        sf = new SettingsFrame();
        alertFrame = new AlertFrame();
        initConfig();
        if (websocketUrl.equals("")) {
            sf.setVisible(true);
        }

        runSocket();
    }

    private static void tmpInit() {
        String tmpdir = System.getProperty("java.io.tmpdir");
        String myTmpDir = tmpdir + NAME;
        FileTool.mkdirs(myTmpDir);
        System.out.println("临时工作目录：" + tmpdir);
        iniPath = myTmpDir + File.separator + "settings.ini";
        logoPath = myTmpDir + File.separator + "logo.gif";
        FileTool.fromJarCopyFile(ClientStatusMonitorApplication.class.getResourceAsStream("/logo.gif"), logoPath);
        offlineWavPath = myTmpDir + File.separator + "offline.wav";
        FileTool.fromJarCopyFile(ClientStatusMonitorApplication.class.getResourceAsStream("/offline.wav"), offlineWavPath);
        offlinePath = myTmpDir + File.separator + "offline.gif";
        FileTool.fromJarCopyFile(ClientStatusMonitorApplication.class.getResourceAsStream("/offline.gif"), offlinePath);
        onlineWavPath = myTmpDir + File.separator + "online.wav";
        FileTool.fromJarCopyFile(ClientStatusMonitorApplication.class.getResourceAsStream("/online.wav"), onlineWavPath);
        onlinePath = myTmpDir + File.separator + "online.png";
        FileTool.fromJarCopyFile(ClientStatusMonitorApplication.class.getResourceAsStream("/online.png"), onlinePath);
    }

    private static void initConfig() {
        File f = new File(iniPath);
        if (!f.exists()) {
            try {
                f.createNewFile();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        try {
            ini = new Wini(f);
            if (ini.containsKey("client")) {
                Ini.Section section = ini.get("client");
                if (section.containsKey("websocketUrl")) {
                    if (!section.get("websocketUrl").equals("")) {
                        websocketUrl = section.get("websocketUrl");
                    }
                    if (!section.get("username").equals("")) {
                        username = section.get("username");
                    }
                    if (!section.get("password").equals("")) {
                        password = section.get("password");
                    }
                }
            }
            sf.setWebsocketUrl(websocketUrl);
            sf.setUsername(username);
            sf.setPassword(password);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void saveConfig(JSONObject data) throws Exception {
        websocketUrl = data.getString("wsurl");
        ini.add("client", "websocketUrl", websocketUrl);
        username = data.getString("username");
        ini.add("client", "username", username);
        password = data.getString("password");
        ini.add("client", "password", password);
        ini.store();
    }

    public static WsSimpleClient wsSimpleClient = null;
    public static volatile boolean isRunning = true;

    public static void runSocket() {
        isRunning = true;
        offLinePlayer = new MyPlayer(offlineWavPath, false, true);
        onLinePlayer = new MyPlayer(onlineWavPath, false, true);
        wsSimpleClient = new WsSimpleClient(websocketUrl + "/services/cstatus", username, password);
        wsSimpleClient.addListener(new SimpleClientMessageAdapter() {
            @Override
            public void call(String body) {
                System.out.println(body);
                try {
                    JSONObject obj = JSON.parseObject(body);
                    if (obj.containsKey("deviceId") && obj.containsKey("status")) {
                        if (!isStopWarning && obj.getString("status").equals("offline")) {
                            offLinePlayer.start();
                            alertFrame.showFrame(obj.getString("deviceId") + "下线啦");
                        } else if (obj.getString("status").equals("online")) {
                            onLinePlayer.start();
                            alertFrame.showFrame(obj.getString("deviceId") + "上线啦");
                        }else{
                            offLinePlayer.stop();
                            onLinePlayer.stop();
                            alertFrame.hideFrame();
                        }
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }

            @Override
            public void close() {
                offLinePlayer.stop();
                onLinePlayer.stop();
                wsSimpleClient.close();
                isRunning = false;
                runSocket();
            }

            @Override
            public void error(String error) {
                isRunning = false;
                runSocket();
            }
        });
        wsSimpleClient.send(new WsPushSubscriptionParam());

        while (!wsSimpleClient.isRunning()) {
            wsSimpleClient.waiting(5);
        }

        try {
            while (isRunning)
                Thread.sleep(5000);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            wsSimpleClient.close();
        }

        runSocket();
    }
}
